package com.easy.modules.sysmgr.web.action;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.easy.common.util.Const;
import com.easy.common.util.date.DateUtils;
import com.easy.common.util.web.BrowserUtils;
import com.easy.common.util.web.IpUtil;
import com.easy.common.util.web.UserAgent;
import com.easy.common.util.web.UserAgentUtil;
import com.easy.common.web.BaseController;
import com.easy.common.web.page.DataGrid;
import com.easy.common.web.page.Msg;
import com.easy.common.web.servlet.ApplicationConstants;
import com.easy.common.web.servlet.ValidateCodeServlet;
import com.easy.modules.sysmgr.service.LoginLogServiceI;
import com.easy.modules.sysmgr.service.UserServiceI;
import com.easy.modules.sysmgr.web.form.GlobalForm;
import com.easy.modules.sysmgr.web.form.LoginLogForm;
import com.easy.modules.sysmgr.web.form.UserForm;
import com.easy.modules.sysmgr.web.form.UserSession;

@Controller
@RequestMapping("/sysmgr/user")
public class UserAction extends BaseController {
	
	@Autowired
	private UserServiceI userService ;
	
	@Autowired
	private LoginLogServiceI loginlogService ;

	
	@RequestMapping("/user_main.do")
	public String user_main(){
		return  Const.SYSMGR + "user_main" ;
	}
	
	@RequestMapping("/user_form.do")
	public String user_form(UserForm form, Model mode){
		if(null != form.getId() && !"".equals(form.getId())) {
			mode.addAttribute("id", form.getId()) ;
		}
		return Const.SYSMGR + "user_form" ;
	}
	
	@RequestMapping("/doNotNeedAuth_search.do")
	public String doNotNeedAuth_search(UserForm form){
		return Const.SYSMGR + "user_search" ;
	}
	
	@RequestMapping("/user_group_page.do")
	public String user_group_page(UserForm form, Model mode){
		mode.addAttribute("ids", form.getIds()) ;
		return Const.SYSMGR + "user_group_page" ;
	}
	
	@RequestMapping("/user_dept_page.do")
	public String user_dept_page(UserForm form, Model mode){
		mode.addAttribute("ids", form.getIds()) ;
		return Const.SYSMGR + "user_dept_page" ;
	}
	
	@RequestMapping("/user_role_page.do")
	public String user_role_page(UserForm form, Model mode){
		mode.addAttribute("ids", form.getIds()) ;
		return Const.SYSMGR + "user_role_page" ;
	}
	
	@RequestMapping("/user_permits_page.do")
	public String user_permits_page(UserForm form, Model mode){
		mode.addAttribute("ids", form.getIds()) ;
		return Const.SYSMGR + "user_permits_page" ;
	}
	
	@RequestMapping("/user_lockAccount_page.do")
	public String user_lockAccount_page(UserForm form, Model mode){
		mode.addAttribute("ids", form.getIds()) ;
		return Const.SYSMGR + "user_lockAccount_page" ;
	}
	
	@RequestMapping("/user_resetPwd_page.do")
	public String user_resetPwd_page(UserForm form, Model mode){
		mode.addAttribute("ids", form.getIds()) ;
		return Const.SYSMGR + "user_resetPwd_page" ;
	}
	
	@RequestMapping("/get.do")
	@ResponseBody
	public UserForm get(UserForm form){
		return this.userService.get(form) ;
	}
	
	@RequestMapping("/add.do")
	@ResponseBody
	synchronized public Msg add(UserForm form){
		return this.userService.save(form) ;
	}
	
	@RequestMapping("/edit.do")
	@ResponseBody
	public Msg edit(UserForm form){
		return this.userService.edit(form) ;
	}
	
	@RequestMapping("/delete.do")
	@ResponseBody
	public Msg delete(UserForm form){
		return this.userService.delete(form) ;
	}
	
	@RequestMapping("/datagrid.do")
	@ResponseBody
	public DataGrid datagrid(UserForm form, HttpServletRequest request, HttpServletResponse response){
		return this.userService.datagrid(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_datagrid.do")
	@ResponseBody
	public DataGrid doNotNeedAuth_datagrid(UserForm form){
		return this.userService.datagrid(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_batch_workgroup.do")
	@ResponseBody
	synchronized public Msg doNotNeedAuth_batchGroup(UserForm form){
		return this.userService.batchUserWorkGroup(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_batch_dept.do")
	@ResponseBody
	synchronized public Msg batchDept(UserForm form){
		return this.userService.batchDept(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_batch_userrole.do")
	@ResponseBody
	public Msg batchRole(UserForm form){
		return this.userService.batchUserRole(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_batch_permits.do")
	@ResponseBody
	public Msg batchPermits(UserForm form){
		return this.userService.batchPermits(form) ;
	}
	
	@RequestMapping("/lockAccount.do")
	@ResponseBody
	public Msg lockAccount(UserForm form){
		return this.userService.lockAccount(form) ;
	}
	
	@RequestMapping("/clearPwd.do")
	@ResponseBody
	public Msg clearPwd(UserForm form){
		return this.userService.clearPwd(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_resetPwd.do")
	@ResponseBody
	public Msg resetPwd(UserForm form){
		return this.userService.resetPwd(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_modifyPwd.do")
	@ResponseBody
	public Msg doNotNeedAuth_modifyPwd(UserForm form){
		return this.userService.modifyPwd(form) ;
	}
	
	@RequestMapping("/doNotNeedAuth_MyAccountInfo.do")
	@ResponseBody
	public Msg doNotNeedAuth_MyAccountInfo(UserForm form, Model model){
		return this.userService.MyAccountInfo(form) ;
	}
	
	private Msg loginCheckLimit(UserForm form, HttpServletRequest request) {
		String ipAddr = IpUtil.getIpAddr(request) ;
		
		GlobalForm globle = (GlobalForm) ApplicationConstants.GLOBAL_MAP.get("global") ; 
		
		//周期+时间段
		if(null != globle.getStartDate() && null != globle.getEndDate() && null != globle.getStartTime() && null != globle.getEndTime()) {
			String startDatetime = DateUtils.format(globle.getStartDate(), DateUtils.TYPE_DATE) +" "+DateUtils.format(globle.getStartTime(), DateUtils.TYPE_TIME) ;
			String endDatetime = DateUtils.format(globle.getEndDate(), DateUtils.TYPE_DATE) +" "+DateUtils.format(globle.getEndTime(), DateUtils.TYPE_TIME) ;
			boolean datetimeScope = DateUtils.datetimeScope(DateUtils.format(new Date(), DateUtils.TYPE_DATETIME), startDatetime, endDatetime, DateUtils.TYPE_DATETIME) ;
			if(datetimeScope) {
				return new Msg(false, "禁止登陆<br>开放登陆时间为：" + DateUtils.format(DateUtils.dateAdd(DateUtils.format(globle.getStartDate(), DateUtils.TYPE_DATE), 1), DateUtils.TYPE_DATE)+" "+DateUtils.format(globle.getEndTime(), DateUtils.TYPE_TIME)) ;
			}
		}
		//时间段
		if(null != globle.getStartTime() && null != globle.getEndTime()) {
			String startTime = DateUtils.format(globle.getStartTime(), DateUtils.TYPE_TIME) ;
			String endTime = DateUtils.format(globle.getEndTime(), DateUtils.TYPE_TIME) ;
			boolean datetimeScope = DateUtils.datetimeScope(DateUtils.format(new Date(), DateUtils.TYPE_TIME), startTime, endTime, DateUtils.TYPE_TIME) ;
			
			if(datetimeScope) {
				return new Msg(false, "禁止登陆<br>开放登陆时间为：" + endTime) ;
			}
		}
		//周期
		if(null != globle.getStartDate() && null != globle.getEndDate()) {
			String startDate = DateUtils.format(globle.getStartDate(), DateUtils.TYPE_DATE) ;
			String endDate = DateUtils.format(globle.getEndDate(), DateUtils.TYPE_DATE) ;
			boolean datetimeScope = DateUtils.datetimeScope(DateUtils.format(new Date(), DateUtils.TYPE_DATE), startDate, endDate, DateUtils.TYPE_DATE) ;
			if(datetimeScope) {
				return new Msg(false, "禁止登陆<br>开放登陆时间为：" + DateUtils.format(DateUtils.dateAdd(endDate, 1), DateUtils.TYPE_DATE)) ;
			}
		}
		//禁止访问的IP
		if(null != globle.getForbidden_ip() && !"".equals(globle.getForbidden_ip())) {
			List<String> forbiddenIP = Arrays.asList(globle.getForbidden_ip().split(","));
			if(forbiddenIP.contains(ipAddr)) {
				return new Msg(false, "该IP["+ipAddr+"]被禁止访问！") ;
			}
		}
		
		return new Msg(true);
	}
	
	@RequestMapping("/login.do")
	@ResponseBody
	public Msg login(UserForm form, HttpServletRequest request){
		
		String valiCode = (String) request.getSession().getAttribute(ValidateCodeServlet.VALIDATE_CODE) ;
		
		if(null == form.getAccount() || "".equals(form.getAccount())) {
			return new Msg(false, "请输入账号!") ;
		}
		if(null == form.getValiCode() || "".equals(form.getValiCode())) {
			return new Msg(false, "请输入验证码!") ;
		}
		
		if(!form.getValiCode().equalsIgnoreCase(valiCode)) {
			return new Msg(false, "验证码不正确!") ;
		}
		UserForm user = this.userService.login(form) ;
		
		if(null != user) {
			if(!"root".equals(user.getAccount())) {
				Msg loginCheckLimit = loginCheckLimit(form, request) ;
				if(!loginCheckLimit.isStatus()) {
					return loginCheckLimit ;
				}
			}
			
			if(null != user && user.getStatus() == 1) {
				return new Msg(false, "该账号被锁定，请联系管理员！") ;
			}
			String ipAddr = IpUtil.getIpAddr(request) ;
			UserSession userSession = new UserSession() ;
			userSession.setId(user.getId()) ;
			userSession.setAccount(user.getAccount()) ;
			userSession.setTruename(user.getTruename()) ;
			userSession.setIp(ipAddr) ;
			userSession.setAuths(this.userService.getMyAuths(user)) ;
			
			request.getSession().setAttribute(Const.USER_SESSION, userSession) ;
			
			//销毁验证码
			request.getSession().removeAttribute(ValidateCodeServlet.VALIDATE_CODE) ;
			
			
			UserAgent userAgent = UserAgentUtil.getUserAgent(BrowserUtils.getAgent(request)) ;
			LoginLogForm lf = new LoginLogForm() ;
			lf.setLoginAccount(user.getAccount()) ;
			lf.setTruename(user.getTruename()) ;
			lf.setLoginTime(new Date()) ;
			lf.setIp(ipAddr) ;
			lf.setBrowserType(userAgent.getBrowserType()) ;
			lf.setBrowserVersion(userAgent.getBrowserVersion()) ;
			lf.setPlatformType(userAgent.getPlatformType()) ;
			this.loginlogService.save(lf) ;
			
			return new Msg(true) ;
		}else {
			return new Msg(false, "该账号不存在或密码错误！") ;
		}
	}
	
	@RequestMapping("/doNotNeedAuth_logout.do")
	@ResponseBody
	public Msg doNotNeedAuth_logout(HttpServletRequest request){
		request.getSession().invalidate() ;
		return new Msg(true, "已注销！") ;
	}
	
}
